package com.example.qxfw.common.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/************************************
 *
 * @author : HuangDeYin Jolly
 * @since : JDK 11
 * @Date : 2023/8/14  星期一   10:25
 * @description : 此类用来 将byte[] 转换为 各种文件存储在resources中
 ***************************************/
@Component
public class ByteToFileUtil {
    private final ResourceLoader resourceLoader;

    @Value("D:\\work\\1\\ly-sjzz (2)\\ly-sjzz\\src\\main\\resources\\grid")
    private String gridFile;

    public ByteToFileUtil(final ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    public String byteArrayToGridFile(byte[] data, String fileName) throws IOException {

        // 获取项目的根目录路径
        String projectPath = resourceLoader.getResource("").getFile().getAbsolutePath();

        // 构建相对于项目的文件路径
        String relativeFilePath = gridFile +"/"+ fileName;

        // 完整文件路径
        String fullFilePath = projectPath + File.separator + relativeFilePath;

        File outputFile = new File(relativeFilePath);

        //File outputFile = new File("src/main/resources/grid/" + fileName);

        if (outputFile.exists()) {
            try (OutputStream outputStream = new FileOutputStream(outputFile, false)) {
                StreamUtils.copy(data, outputStream); // 覆盖写入文件
            }
        } else {
            try (OutputStream outputStream = new FileOutputStream(outputFile, true)) {
                StreamUtils.copy(data, outputStream); // 追加写入文件
            }
        }

        return outputFile.getAbsolutePath(); // 返回文件的绝对路径
    }

}
